#!/usr/bin/env python
# Author: Derek Green

PKG = 'nltk_parser'

import roslib; roslib.load_manifest(PKG)
import rospy
import nltk
import os
from nltk_parser.srv import *

# use nltk as a service
class NltkParser():
    def __init__(self):
        rospy.init_node('ntlk_parser_service', anonymous=True)
        self.service = rospy.Service('nltk_parse', Parse, self.handle_parse_request)
        self.path = os.path.join(rospy.get_param("/nltk_parser_service/grammar_path"), "grammars", rospy.get_param("/nltk_parser_service/grammar_name"))
        self.grammar = nltk.data.load('file:%s'%self.path)
        self.parser = nltk.ChartParser(self.grammar)
        rospy.spin()

    def handle_parse_request(self, request):
        parse_tree = "ERROR"
        try:
            print "NltkParser processing string: \"" + request.speech_txt + "\""
            tokens = nltk.word_tokenize(request.speech_txt)
            trees = self.parser.nbest_parse(tokens)
            parse_tree = str(trees[0])
#            for tree in trees:
#                print tree
#            print "*****************************************"
            print "ParserNltk currently returning best parse only."
        except rospy.ServiceException, e:
            print "ParserNltk, ServiceException: %s"%e
        except Exception, e:
            print "ParserNltk Exception: %s"%e
        return parse_tree

if __name__ == '__main__':
    try:
        n = NltkParser()
        rospy.spin()
    except rospy.ROSInterruptException: pass

